import {defineStore} from 'pinia'
import {getRouteList} from "@/api/system"
import {generatorRouter, getMenuListByRoute} from "@/routes/index"
import {RouteRecordRaw} from "vue-router"
import router from '@/routes/index'
export interface MapState {
  frontRoutes: Array<RouteRecordRaw>;
  backRoutes: Array<RouteRecordRaw>;
  frontMenu: Array<RouteRecordRaw>;
  backMenu: Array<RouteRecordRaw>;
}
export const routeStore =  defineStore('routeStore',{
	state:():MapState=>{
		return{
			frontRoutes:[],
			backRoutes:[],
			frontMenu:[],
			backMenu:[]
		}
	},
	actions:{
		/**
		 * 如果通过接口获取了路由，则说明新加的路由  返回true 否则返回false
		 */
		getRoutes(menuType:Number,roleIds:String){
			return new Promise(async (resolve,reject)=>{
				getRouteList({menuType,roleIds}).then(res=>{
					if(res.data && res.data.length > 0){
						const currentRoutes:Array<RouteRecordRaw> = generatorRouter(res.data)
						currentRoutes.push({
							path: '/:pathMatch(.*)',
							redirect: '/404'
						})
						currentRoutes.push({
							path: '/:catchAll(.*)',
							redirect: '/404'
						})
						
						if(menuType == 1){
							this.frontRoutes = currentRoutes;
						}else{
							this.backRoutes = currentRoutes;
						}
						currentRoutes.forEach((routeItem:RouteRecordRaw)=>{
							router.addRoute(routeItem)
						})
						resolve(true)
					}else{
						resolve(false)
					}
				}).catch((e)=>{
					reject(e)
				})
			})
		},
		getMenuList(menuType:Number,roleIds:String){
			return new Promise(async (resolve,reject)=>{
				getRouteList({menuType,roleIds}).then(res=>{
					if(res.data && res.data.length > 0){
						const currentMenu:Array<RouteRecordRaw> = getMenuListByRoute(res.data,'')
						if(menuType == 1){
							this.frontMenu = currentMenu
							return
						}else{
							this.backMenu = currentMenu
						}
						resolve(currentMenu)
					}else{
						resolve([])
					}
				}).catch((e)=>{
					reject(e)
				})
			})
		},
		
		clearRoutes(menuType:Number){
			if(menuType === 1){
				this.backRoutes = []
			}else{
				this.frontRoutes = []
			}
		}
	}
})